package com.freesun.shop.service.impl;

import com.freesun.shop.service.SmsPushService;
import com.github.qcloudsms.SmsSingleSender;
import com.github.qcloudsms.SmsSingleSenderResult;
import com.github.qcloudsms.httpclient.HTTPException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

import java.io.IOException;

@Service
public class SmsPushServiceImpl implements SmsPushService {
    private static Logger logger = LoggerFactory.getLogger(SmsPushServiceImpl.class);

    @Autowired
    private SmsSingleSender smsSingleSender;


    // 短信模板 ID，需要在短信应用中申请
    int templateId = 464726; // NOTE: 这里的模板 ID`7839`只是示例，真实的模板 ID 需要在短信控制台中申请
    // 签名

    @Override
    public void pushSms(String content) {
        Assert.notNull(content,"传入短信内容不能为Null");
        if(!StringUtils.hasText(content)||!content.contains("##")){
            throw new RuntimeException("验证码格式错误");
        }
        String[] contents = content.split("##");
        // 需要发送短信的手机号码
        String[] phoneNumbers = {contents[0]};
        String[] parm={contents[1]};
        String smsSign = "自由阳光"; // NOTE: 签名参数使用的是`签名内容`，而不是`签名ID`。
        SmsSingleSenderResult result = null;
        try {
            result = smsSingleSender.sendWithParam("86", phoneNumbers[0],
                    templateId, parm, smsSign, "", "");
        } catch (HTTPException | IOException e) {
            e.printStackTrace();
            logger.info("短信发送失败,原因是:{}",result);
        }
        logger.info("短信发送成功,结果是:{}",result);
    }
}
